<?php

namespace App\Admin\Actions\NewsAction;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use OpenAI;
use Rainsens\Dinglog\Facades\Dinglog;
use App\Jobs\TranslateVideoJob;
use App\Supports\LinkedIn\Client;
use GuzzleHttp\Client as GClient;

class VideoShareToLinkedin extends RowAction
{
    public $name = '视频分享到linkedin';
    
    public function handle(Model $model)
    {

    	$user = User::find(1);
				
		$client = new Client(
		    getenv('LINKDIN_CLIENT_ID'),
		    getenv('LINKDIN_CLIENT_SECRET'),
		);
		$client->setRedirectUrl('https://www.xbreakingtechinsight.com');
		
		$client->setAccessToken($user->linkdin_token);

		$id ="urn:li:video:D5610AQGFK_kGT_ldXA";
		$uploadUrl = "https://api.linkedin.com/rest/videos/".$id;
		

		/* $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $uploadUrl);
	    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
	    curl_setopt($ch, CURLOPT_HTTPHEADER, [
	        'Authorization: Bearer ' . $user->linkdin_token,
	        'Linkedin-Version: 202504',
	        'Content-Type: application/json',
	    ]);
	    $response = curl_exec($ch);
	  */


		if($model->translate_video_url){

		 	$videoPath = $model->translate_video_url;
		 }else{

		 	$videoPath = img_path($model->video_url);
		 }

		  $video = file_get_contents($videoPath);



		$uploadUrl = 'https://api.linkedin.com/rest/videos?action=initializeUpload';
	    $requestData = [
	        'initializeUploadRequest' => [
	            'owner' => 'urn:li:organization:100897090',
	            "fileSizeBytes"=> strlen($video),
		        "uploadCaptions"=> false,
		        "uploadThumbnail"=> false
	        ],
	    ];




	     $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $uploadUrl);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_POST, true);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
	    curl_setopt($ch, CURLOPT_HTTPHEADER, [
	        'Authorization: Bearer ' . $user->linkdin_token,
	        'Linkedin-Version: 202504',
	        'Content-Type: application/json',
	    ]);
	    $response = curl_exec($ch);

	   
	    // get asset id
	    $responseArray = json_decode($response, true);
	    

	    $assetId = $responseArray['value']['video'];
    
	    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	    curl_close($ch);
	    

	    if ($httpCode == 200) {
	        // upload picture to url received in response
	       	

	       	 $client = new Client();
	       	 $uploadPartIds= [];
   
	    	foreach($responseArray['value']['uploadInstructions'] as $k=>$v){


	    		$uploadUrl = $v['uploadUrl'];

	    		$len = $v['lastByte'] - $v['firstByte'] +1;
	    		$thisVideo = substr($video, $v['firstByte'], $len);
	    		//$thisVideo = $video;

	    		 $fileHandler = fopen($videoPath, 'r');

	    		// dd($fileHandler);
	    		$client = new GClient();
	    		$chunkedUpload = $client->put($uploadUrl, [
		            'headers' => [
		                'Content-Type' => 'application/octet-stream',
		                'Authorization' => 'Bearer ' . $user->linkdin_token,
		                'LinkedIn-Version' => '202405'
		            ],
		            'body' => $thisVideo,
		        ]);

	    	    $uploadPartIds[] = $chunkedUpload->getHeader('ETag')[0];

		        /*$ch = curl_init();
		        curl_setopt($ch, CURLOPT_URL, $uploadUrl);
		        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
		        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		        curl_setopt($ch, CURLOPT_POSTFIELDS, $thisVideo);
		        curl_setopt($ch, CURLOPT_HEADER, true); // 设置为true以包含头部信息在输出
		        curl_setopt($ch, CURLOPT_HTTPHEADER, [
		            'Authorization: Bearer '.$user->linkdin_token,
		            'Linkedin-Version: 202504',
		            'Content-Type:application/octet-stream'
		        ]);
		        $response = curl_exec($ch);

		        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
				$header = substr($response, 0, $header_size);
				$headerArr = [];
				$headerArr = explode("\r\n",$header);
				

				dd($headerArr);
				if(isset($headerArr[4])){

					$ETag = str_replace("ETag: ","",$headerArr[4]);
					$uploadedPartIds[$k] = $ETag;
				}
*/

				
		        //

		        curl_close($ch);

	    	}

	    	

	    	$finalUrl = "https://api.linkedin.com/rest/videos?action=finalizeUpload";

	    	 $finalRequestData = [
		        'finalizeUploadRequest' => [
		            'video' => $assetId,
		            "uploadToken"=> '',
			        "uploadedPartIds"=> $uploadPartIds,
		        ],
		    ];


    	    $ch = curl_init();
		    curl_setopt($ch, CURLOPT_URL, $finalUrl);
		    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($ch, CURLOPT_POST, true);
		    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($finalRequestData));
		    curl_setopt($ch, CURLOPT_HTTPHEADER, [
		        'Authorization: Bearer ' . $user->linkdin_token,
		        'Linkedin-Version: 202504',
		        'Content-Type: application/json',
		    ]);
		    $response = curl_exec($ch);

	        
	        
	    }
	    sleep(5);

	    $postUrl = 'https://api.linkedin.com/rest/posts';
	    $postData = [
	        'author' => 'urn:li:organization:100897090',
	        "commentary"=>$model->brief_en ?? $model->brief,
	        'visibility' => 'PUBLIC',
	        'distribution' => [
	            'feedDistribution' => 'MAIN_FEED',
	            'targetEntities' => [],
	            'thirdPartyDistributionChannels' => []
	        ],
	        'content' => [
	            'media' => [
	            	'title' => $model->title_en ?? $model->title,
	                'id' => $assetId,
	                
	            ]
	        ],
	        'lifecycleState' => 'PUBLISHED',
	        'isReshareDisabledByAuthor' => false
	    ];

	    $headers = [
	        'Authorization: Bearer '. $user->linkdin_token,
	        'X-Restli-Protocol-Version: 2.0.0',
	        'Linkedin-Version: 202504',
	        'Content-Type: application/json',
	    ];
	   
	    $ch = curl_init($postUrl);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_POST, true);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	    $response = curl_exec($ch);
	    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
	    $responseHeaders = substr($response, 0, $headerSize);

	   


	    curl_close($ch);


	    return $this->response()->success('视频分享成功')->refresh();
	    dd($assetId);
	    $arr = [                                   
            'author' => 'urn:li:organization:100897090',
            'lifecycleState' => 'PUBLISHED',
            'specificContent' => [          
                'com.linkedin.ugc.ShareContent' => [
                    'shareCommentary' => [
                        'text' => "cs"
                    ],
                    'shareMediaCategory' => 'ARTICLE',
                    'media' => [
                        [
                            'status' => 'READY',
                            'description' => [
                                'text' => 'aaaaaaa'
                            ],
                            'thumbnail'=>$assetId,

                            //img_path($new['images']
                            
                            'title' => [
                                'text' => '333333'
                            ]
                        ]
                    ]
                ]
            ],
            'visibility' => [
                'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC'
            ]
        ];

       //var_dump($arr); die;
$share = $client->post(                 
        'ugcPosts',                         
        $arr
    );

	    dd($share);

		 $media = $register['value']['asset'];

		 if($model->translate_video_url){

		 	$url = $model->translate_video_url;
		 }else{

		 	$url = $model->video_url;
		 }
         

         $linkedInClient = new GClient();

		$response = $linkedInClient->post(
		        $register['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'], [
		            'headers' => [
		                'Accept'                => 'application/json',
		                'Authorization'         => 'Bearer '.$user->linkdin_token,
		            ],
		            'multipart' => [
		                [
		                    'name'     => 'upload-file',
		                    'contents' => file_get_contents(img_path('/images/mI2lxQwKZ0Ii0EdOW2PhYTTdVfO3Iz5CL0cKUgQf.jpg')),
		                ],
		            ],
		        ]
		    );

		dd($response);

            $headers = array();
            $headers[] = 'Authorization: Bearer '.$user->linkdin_token;// token generated above code
            $headers[] = 'X-Restli-Protocol-Version: 2.0.0';
            $headers[] = 'Content-Type: data/binary';
            $headers[] = 'Content-Length: 0';


            $ch = curl_init();
            $options = array(
                CURLOPT_HEADER => true,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_URL => $register['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_POST => true,
                CURLOPT_SAFE_UPLOAD => true,
                CURLOPT_POSTFIELDS => $postfield
            );
            curl_setopt_array($ch, $options);
            $imgResponse = curl_exec($ch);
            if (curl_error($ch)) {
                $error_msg = curl_error($ch);
            }
            $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            dd($imgResponse);
           /* $assets = explode(":", $media);
            
            $assetRequest = $adapter->apiRequest('assets/'.$assets[3], 'GET');*/

/*3. Create the image share.*/

           // $status = $this->imagePostArray($data, $media);
	   	
	    //dispatch(new TranslateVideoJob($model))->onQueue('vnews');

	    //return $this->response()->success('视频正在分享，请耐心等待')->refresh();
    }

   
	public function dialog()
	{
		$this->confirm('确定分享该内容吗?');
	}
}
